﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Moki.Exceptions;

namespace Moki.Core
{
    /// <summary>
    /// Creates matchers array for arguments.
    /// </summary>
    internal class MatchersBuilder
    {
        private static bool firstInitOccured = false;      
        private static List<KeyValuePair<Matcher, int>> matcherAtPosition = new List<KeyValuePair<Matcher, int>>();
        private static int CurrentPosition { get; set; }

        /// <summary>
        /// Initializes position for new matcher.
        /// </summary>
        public static void InitNewPostition()
        {
            if (!firstInitOccured)
            {
                firstInitOccured = true;
                return;
            }
            else
                CurrentPosition++;
        }

        public static void AddMatcherAtCurrentPosition(Matcher matcher)
        {
            if (!firstInitOccured)
                InitNewPostition();

            matcherAtPosition.Add(new KeyValuePair<Matcher, int>(matcher, CurrentPosition));
        }

        /// <summary>
        /// Gets created matcher array.
        /// </summary>
        /// <returns></returns>
        public static Matcher[] GetMatchersArray()
        {
            Matcher[] matchers;

            if (firstInitOccured)
                matchers = new Matcher[CurrentPosition + 1];
            else
                matchers = new Matcher[CurrentPosition];

            try
            {
                matcherAtPosition.ForEach(m => matchers[m.Value] = m.Key);
            }
            catch (Exception ex)
            {
                throw new CustomArgumentException("Can't resolve custom argument. " + ex.Message);
            }

            return matchers;
        }

        /// <summary>
        /// Resets matchers list.
        /// </summary>
        public static void Reset()
        {
            CurrentPosition = 0;
            firstInitOccured = false;
            matcherAtPosition = new List<KeyValuePair<Matcher, int>>();
        }
    }
}
